﻿using System.Collections;
using System.Windows.Forms;

namespace AI3SaveEditor
{
    public class ListViewHelper
    {
        public static void ListView_ColumnClick(object sender, ColumnClickEventArgs e) {
            ListView listView = sender as ListView;
            ListViewColumnSorter sorter = listView.ListViewItemSorter as ListViewColumnSorter;
            if (e.Column == sorter.SortColumn) {
                sorter.SortOrder = sorter.SortOrder == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
            }
            else {
                sorter.SortColumn = e.Column;
                sorter.SortOrder = SortOrder.Ascending;
            }
            listView.Sort();
        }
    }

    public class ListViewColumnSorter : IComparer
    {
        public int SortColumn { set; get; }
        public SortOrder SortOrder { set; get; }
        private CaseInsensitiveComparer comparer;

        public ListViewColumnSorter() {
            SortColumn = 0;
            SortOrder = SortOrder.None;
            comparer = new CaseInsensitiveComparer();
        }

        public int Compare(object x, object y) {
            if (SortOrder == SortOrder.None)
                return 0;

            ListViewItem listviewX, listviewY;
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;
            int compareResult = comparer.Compare(listviewX.SubItems[SortColumn].Text, listviewY.SubItems[SortColumn].Text);

            return (SortOrder == SortOrder.Ascending) ? compareResult : -compareResult;
        }
    }
}
